package ru.aptu.billing_server;

import ru.aptu.billing_message.*;

/**
 * Created by IntelliJ IDEA.
 * User: andrey
 * Date: 2/8/12
 * Time: 12:53 PM
 */

public class AdvancedBillingServer extends BillingServer {

    protected static final double LAST_VALUE = 100.0;

    protected static final double RATE = 2.5;

    protected static final String CURRENCY = "RUB";


    public AdvancedBillingServer( String host, int port) {
        super(port, host);
    }

    @Override
    protected ResponseMessage handleAccountMessage(RequestMessage message) {
        if (message.isServiceCredit()) {
            return new ResponseCreditMessage(message, BasicMessage.Status.OK, LAST_VALUE, RATE, CURRENCY);
        } else {
            return new ResponseMessage(message, BasicMessage.Status.OK);
        }
    }

    @Override
    protected ResponseMessage handleTransactionMessage(RequestMessage message) {
        PaymentRequestMessage msg = (PaymentRequestMessage) message;

        synchronized (monitor) {
            if (transactions.contains(msg.getTransaction())) {
                return new ResponseMessage(message, BasicMessage.Status.DUPLICATE_TRN);
            } else {
                transactions.add(msg.getTransaction());
                if (msg.isServiceCredit()) {
                    if (msg.getAmount() < 0) {
                        return new ResponseMessage(msg, BasicMessage.Status.BAD_AMOUNT);
                    } else if (!msg.getCurrency().equals(CURRENCY)) {
                        return new ResponseMessage(msg, BasicMessage.Status.BAD_CURRENCY);
                    } else {
                        return new ResponseMessage(message, BasicMessage.Status.OK);
                    }
                } else {
                    return new ResponseMessage(message, BasicMessage.Status.OK);
                }
            }
        }
    }

}
